<!-- 心灵保健 -->
<template>
	<view class="contaier" :style="{ minHeight: getHeight + 'px' }">
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">宾州担忧问卷（PSWQ）</block>
		</cu-custom>
		
	<!-- 	<view class="bannerBox">
			<image class="ggBox" mode="widthFix" src="http://cdn.zhoukaiwen.com/Banner3.jpg"></image>
		</view> -->
		
		<view style="height: 250rpx;width: 1rpx;"></view>
		<!-- 答题主页面 -->
		<view class="padding">
			<view class="mainBox radius shadow-warp bg-white margin-top relative">
				<view class="userHeard cu-avatar lg round" style="background-image:url(http://cdn.zhoukaiwen.com/logo.png);"></view>
				<view v-show="hasData">
					<view class="animation-reverse shadow" :class="animation" data-class="slide-rights" v-if="DataList[num].serialNumber">
						<view class="mentalTitle text-xl text-black text-bold">
							<text>{{ DataList[num].serialNumber || '' }}</text>
							<text>、</text>
							<text>{{ DataList[num].title || '' }}</text>
						</view>
						<view class="mentalList" v-for="(item, index) in DataList[num].itemList" v-bind:class="{ mentalListActive: index == mentalListActive }"
						 @tap="Toggle(index)">
						 <view @click="answerchoose(DataList[num].serialNumber,index,item.answer)">
							<view class="indexBox text-shadow">{{ item.number || '' }}</view>
							{{ item.answer || '' }}
						</view>
						</view>
					</view>

					<u-line color="#dddddd"></u-line>

					<view class="margin-top cu-progress radius striped active">
						<view class="bg-blue" :style="[{ width: loading ? progress + '%' : '' }]">{{  progress }}%</view>
					</view>
					<view class="explainMain">本测试仅提供参考（答题自动保存在本地，支持中途退出）</view>
				</view>

				<view v-show="noData">
					<view class="text-center text-bold text-black text-xxl margin-tb-xl">您已答题，感谢参与</view>
					<view class="text-center margin-tb-lg text-lg"><h3>IIMedGPT评测结果：</h3>来源：总分：{{showMessage.total_score}}分，担忧水平：{{showMessage.worry_level}}</view>
					<!-- <view class="text-gray text-center margin-tb-lg text-lg">题库正在更新中...</view> -->
				</view>
			</view>
		</view>

		<view class="explain">
			<!-- <view class="integral">您当前积分：{{currentPoints}}分</view> -->
			<view @click="goExplain">
				<u-icon name="question-circle-fill" size="30"></u-icon>
				答题规则说明
			</view>
				<!-- {{useranswers}} -->
		</view>

		<!-- 遮罩层 -->
		<u-mask :show="show">
			<view class="warp">
				<view class="rect" @tap.stop>
					<view class="closeBtn">
						<u-icon @click="closeMask" name="close-circle-fill" color="#ccc" size="58"></u-icon>
					</view>

					<view class="closeImg">
						<image mode="aspectFit" src="http://cdn.zhoukaiwen.com/answerTrophy.png"></image>
					</view>
					<view class="text-black text-bold text-center">恭喜您！完成答题！</view>
					<view class="text-center margin-tb-lg text-gray">总分：{{showMessage.total_score}}分，担忧水平：{{showMessage.worry_level}}</view>

				<!-- 	<view style="width: 350rpx; margin: 50rpx auto 0;">
						<button v-if="isShare != 1" @click="shareBtn" open-type="share" class="cu-btn round bg-blue shadow" style="width: 100%;">分享获得10个积分</button>
						<button v-if="isShare == 1" open-type="share" class="cu-btn round bg-blue shadow" style="width: 100%;">分享给好友</button>
					</view> -->
				</view>
			</view>
		</u-mask>
	</view>
</template>

<script>
	
	export default {
		data() {
			return {
				show: false,
				getHeight: '',
				loading: false,
				animation: '',

				mentalListActive: -1,
				noData: false,
				hasData: true,

				// 数据
				num: 0,
				DataList: [
  {
    "serialNumber": "1",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "假如我没有足够时间去做每一件事情，我不会(因此)而忧虑。(反问题)",
    "itemList": [
      {"number": "A", "answer": "完全不符合"},
      {"number": "B", "answer": "有点不符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "非常符合"},
      {"number": "E", "answer": "完全符合"}
    ]
  },
  {
    "serialNumber": "2",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "我的忧虑淹没了我。",
    "itemList": [
      {"number": "A", "answer": "完全符合"},
      {"number": "B", "answer": "非常符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "有点不符合"},
      {"number": "E", "answer": "完全不符合"}
    ]
  },
  {
    "serialNumber": "3",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "我比较不会去忧虑一些事。(反问题)",
    "itemList": [
      {"number": "A", "answer": "完全不符合"},
      {"number": "B", "answer": "有点不符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "非常符合"},
      {"number": "E", "answer": "完全符合"}
    ]
  },
  {
    "serialNumber": "4",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "许多情况会使我忧虑。",
    "itemList": [
      {"number": "A", "answer": "完全符合"},
      {"number": "B", "answer": "非常符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "有点不符合"},
      {"number": "E", "answer": "完全不符合"}
    ]
  },
  {
    "serialNumber": "5",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "我知道我不应该忧虑某些事，但是我就是没办法控制。",
    "itemList": [
      {"number": "A", "answer": "完全符合"},
      {"number": "B", "answer": "非常符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "有点不符合"},
      {"number": "E", "answer": "完全不符合"}
    ]
  },
  {
    "serialNumber": "6",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "当我面对压力时，我会很忧虑。",
    "itemList": [
      {"number": "A", "answer": "完全符合"},
      {"number": "B", "answer": "非常符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "有点不符合"},
      {"number": "E", "answer": "完全不符合"}
    ]
  },
  {
    "serialNumber": "7",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "我总是担心着某些事。",
    "itemList": [
      {"number": "A", "answer": "完全符合"},
      {"number": "B", "answer": "非常符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "有点不符合"},
      {"number": "E", "answer": "完全不符合"}
    ]
  },
  {
    "serialNumber": "8",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "我发现我可以轻易的停止忧虑的想法。(反问题)",
    "itemList": [
      {"number": "A", "answer": "完全不符合"},
      {"number": "B", "answer": "有点不符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "非常符合"},
      {"number": "E", "answer": "完全符合"}
    ]
  },
  {
    "serialNumber": "9",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "当我完成了某一项工作，我就会开始忧虑其他要做的事情。",
    "itemList": [
      {"number": "A", "answer": "完全符合"},
      {"number": "B", "answer": "非常符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "有点不符合"},
      {"number": "E", "answer": "完全不符合"}
    ]
  },
  {
    "serialNumber": "10",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "我从不忧虑任何事。(反问题)",
    "itemList": [
      {"number": "A", "answer": "完全符合"},
      {"number": "B", "answer": "非常符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "有点不符合"},
      {"number": "E", "answer": "完全不符合"}
    ]
  },
  {
    "serialNumber": "11",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "当我无能为力时，我就不会再去担心它。",
    "itemList": [
      {"number": "A", "answer": "完全不符合"},
      {"number": "B", "answer": "有点不符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "非常符合"},
      {"number": "E", "answer": "完全符合"}
    ]
  },
  {
    "serialNumber": "12",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "我一生都很忧虑。",
    "itemList": [
      {"number": "A", "answer": "完全符合"},
      {"number": "B", "answer": "非常符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "有点不符合"},
      {"number": "E", "answer": "完全不符合"}
    ]
  },
  {
    "serialNumber": "13",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "我注意到我总是在担心事情。",
    "itemList": [
      {"number": "A", "answer": "完全符合"},
      {"number": "B", "answer": "非常符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "有点不符合"},
      {"number": "E", "answer": "完全不符合"}
    ]
  },
  {
    "serialNumber": "14",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "我一旦开始忧虑,就没有办法停止。",
    "itemList": [
      {"number": "A", "answer": "完全符合"},
      {"number": "B", "answer": "非常符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "有点不符合"},
      {"number": "E", "answer": "完全不符合"}
    ]
  },
  {
    "serialNumber": "15",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "我总在忧虑。",
    "itemList": [
      {"number": "A", "answer": "完全符合"},
      {"number": "B", "answer": "非常符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "有点不符合"},
      {"number": "E", "answer": "完全不符合"}
    ]
  },
  {
    "serialNumber": "16",
    "name": "宾州担忧问卷（PSWQ）",
    "title": "除非计划完成不然我会很担心",
    "itemList": [
      {"number": "A", "answer": "完全符合"},
      {"number": "B", "answer": "非常符合"},
      {"number": "C", "answer": "基本符合"},
      {"number": "D", "answer": "有点不符合"},
      {"number": "E", "answer": "完全不符合"}
    ]
  }
]
					,
					useranswers:{   
    "user_id": "1",
	"idd":"",
    "answers": {
        "q1": "3",
        "q2": "2",
        "q3": "1",
        "q4": "5",
        "q5": "2",
        "q6": "1",
        "q7": "3",
        "q8": "2",
        "q9": "1",
        "q10": "5",
        "q11": "3",
        "q12": "2",
        "q13": "1",
        "q14": "5",
        "q15": "2",
        "q16": "1"
    }
},
				setData: {
					// {
					// 	"surveyId": 1,
					// 	"chooses": [{
					// 			"serialNumber": 1,
					// 			"number": 1
					// 		}
					// 	]
					// }
				},

				//进度条
				progress: 0,

				currentPoints: 0, //当前积分
				isShare: 3, //是否分享	0否 1是
userinfo:"",
				showMessage: '' //答题结果

			};
		},
		onShareAppMessage(res) {
			return {
				title: '我已完成答题，快来参与吧'
			};
		},
		onLoad(options) {
			// options 是一个对象，包含传递的所有参数
			const idd = options.id;  // 获取传递的 id 参数
			console.log('传递过来的 id:', idd);
			this.useranswers.idd=idd
			const that = this;
			uni.getSystemInfo({
				success: function(res) {
					that.getHeight = res.windowHeight;
				}
			});
			setTimeout(function() {
				that.loading = true;
			}, 300);

			this.getData();
		},
		watch: {
			progress(val) {
				console.log(this.progress + '% - 进度');

				if (this.progress == 100) {
					
					console.log("答题结束啦");
										
									
					uni.request({
					    url: 'http://202.127.200.31:30010/scale/calculate_pswq', // 请求的URL
					    method: 'POST',
					    data: this.useranswers, // 发送的数据，这里使用的是组件中的useranswers数据
					    header: {
					        'Content-Type': 'application/json' // 设置请求头为JSON格式
					    },
					    success: (res) => {
					        console.log('提交成功:', res.data);
					        this.showMessage = res.data; // 将返回的数据保存到组件的showMessage中
							uni.removeStorageSync('timucach5');
							uni.removeStorageSync('numcach5');
					    },
					    fail: (err) => {
					        console.error('提交失败:', err);
					    }
					});
					this.noData = true;
					this.hasData = false;
					setTimeout(() => {
						this.show = true;
					}, 1300);
				}
			}
		},
		mounted() {
		    // 获取用户信息
		    this.userinfo = uni.getStorageSync("userinfo");
		    if (this.userinfo && this.userinfo.data && this.userinfo.data.userid) {
		        this.useranswers.user_id = this.userinfo.data.userid;
		    }
		    console.log(this.userinfo);
		
		    // 获取缓存的题目和答案数据
		    let numcach = uni.getStorageSync("numcach5");
		    let timucach = uni.getStorageSync("timucach5");
			
		    // 检查数据是否完整
		    if (numcach && timucach) {
		        // 显示弹窗询问用户是否恢复进度
		        uni.showModal({
		            title: '提示',
		            content: '检测到您有历史答题未完成，是否恢复之前的答题进度（取消将重新答题）？',
		            success: (res) => { // 使用箭头函数以保持this上下文
		                if (res.confirm) {
		                    console.log('用户点击确定');
		                    this.num = numcach;
		                    this.useranswers = timucach;
		                    console.log("********************************");
		                    console.log(numcach);
		                    console.log(timucach);
		                    console.log("********************************");
		                } else if (res.cancel) {
							uni.removeStorageSync('timucach5');
							uni.removeStorageSync('numcach5');
		                    console.log('用户点击取消');
		                    // 如果用户取消，可以在此处添加逻辑，例如增加页码，执行动画等
		                    setTimeout(() => {
		                        this.animation = 'animation-slide-left';
		                        this.num=0; // 翻到下一页
		                        setTimeout(() => {
		                            this.mentalListActive = -1;
		                            this.animation = '';
		                        }, 100);
		                    }, 300);
		                }
		            }
		        });
		    } else {
		        // 如果数据不完整，可以选择不做任何事，或者执行其他逻辑，如跳转到登录页面等
				setTimeout(() => {
				    this.animation = 'animation-slide-left';
				    this.num=0; // 翻到下一页
				    setTimeout(() => {
				        this.mentalListActive = -1;
				        this.animation = '';
				    }, 100);
				}, 300);
		    }
		},
		methods: {
			answerchoose(serialNumber,daan,number) {
				console.log(serialNumber,daan,number)
				// 假设useranswers是一个全局对象
			
				// 构造问题的键名
				let questionKey = `q${serialNumber}`;
							
				// 检查该问题是否存在于答案对象中
				if (this.useranswers.answers.hasOwnProperty(questionKey)) {
				    // 如果存在，更新答案
					if(questionKey=='q1')
					{
						this.useranswers.answers[questionKey] = parseInt(daan);
					}
				    else{this.useranswers.answers[questionKey] = parseInt(daan);}
				    console.log('Answer updated:', questionKey, daan);
				} else {
				    // 如果问题键不存在，打印错误信息
				    console.error('Invalid question serial number:', serialNumber);
				}
			},
			getData() {
				this.progress = 0;
			},
			Toggle(index) {
				// 中途保存
				uni.setStorageSync("numcach5", this.num+1);
				uni.setStorageSync("timucach5", this.useranswers);
				this.mentalListActive = index;
				console.log(this.num + 1);
				console.log('length:',this.DataList.length)
				this.progress = (100 / this.DataList.length) * (this.num + 1); //进度条

				if (this.progress < 100) {
					setTimeout(() => {
						this.animation = 'animation-slide-left';
						this.num++; //翻第二页
						setTimeout(() => {
							this.mentalListActive = -1;
							this.animation = '';
						}, 100);
					}, 300);
				} else {
					console.log('没有下一题了');
					this.show = true;
				}
			},
			// 弹窗消失
			closeMask() {
				this.show = false;
			},
			goExplain() {
				uni.navigateTo({
					url: './explain'
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	@import '@/colorui/animation.css';

	.warp {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.rect {
		width: 480rpx;
		// height: 520rpx;
		border-radius: 20rpx;
		padding: 25rpx 25rpx 80rpx 25rpx;
		box-sizing: border-box;
		background-color: #fff;
	}

	.closeImg {
		width: 100%;
		height: 200rpx;
		margin: 10rpx auto 30rpx;

		image {
			height: 200rpx;
		}
	}

	.cu-bar .cu-avatar:first-child {
		margin-left: -11px;
	}

	.cu-bar {
		height: 90rpx !important;
	}

	.mainBox {
		padding: 60rpx 40rpx 20rpx 40rpx;
	}

	.explainMain {
		width: 100%;
		text-align: center;
		font-size: 24rpx;
		text-align: center;
		color: #999999;
		margin-top: 30rpx;
	}

	.userHeard {
		position: absolute;
		left: 50%;
		top: -50rpx;
		margin-left: -50rpx;
	}

	.mentalTitle {
		margin: 0 0 30rpx 0;
	}

	.mentalList {
		width: 100%;
		height: 78rpx;
		line-height: 78rpx;
		padding-right: 20rpx;
		border-radius: 12rpx;
		margin: 30rpx 0;
		overflow: hidden;
		border: 1px solid #dddddd;

		.indexBox {
			width: 70rpx;
			height: 78rpx;
			text-align: center;
			line-height: 78rpx;
			float: left;
			background-color: #dddddd;
			margin-right: 15rpx;
		}
	}

	.mentalListActive {
		width: 100%;
		height: 78rpx;
		line-height: 78rpx;
		padding-right: 20rpx;
		border: 1px solid #0081ff;
		border-radius: 12rpx;
		color: #0081ff;
		margin: 30rpx 0;
		font-weight: 600;
		background-image: url(http://cdn.zhoukaiwen.com/answerYes.png);
		background-repeat: no-repeat;
		background-size: 38rpx;
		background-position: right 30rpx center;

		.indexBox {
			background-color: #0081ff;
			color: #ffffff;
		}
	}

	.contaier {
		background-color: #f2f2f2;

		.bannerBox {
			width: 750rpx;

			image {
				width: 750rpx;
			}
		}

		.explain {
			width: 750rpx;
			// position: absolute;
			bottom: 40rpx;
			font-size: 24rpx;
			margin: 10rpx 0 40rpx 0;
			text-align: center;
			color: #999999;

			.integral {
				font-size: 30rpx;
				margin-bottom: 15rpx;
				color: #333333;
			}
		}
	}
</style>
